from flask import Blueprint, request, jsonify, current_app
import os
import sys
import traceback

# 处理相对导入问题
try:
    # 尝试相对导入（作为包的一部分运行时）
    from .idphoto_processor import process_id_photo
    from werkzeug.utils import secure_filename
except ImportError:
    # 如果相对导入失败，尝试绝对导入（直接运行时）
    try:
        # 添加项目根目录到路径
        sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
        from idphoto.idphoto_processor import process_id_photo
        from werkzeug.utils import secure_filename
    except ImportError:
        # 如果还失败，尝试使用当前目录
        from idphoto_processor import process_id_photo
        from werkzeug.utils import secure_filename

# 创建蓝图
idphoto_bp = Blueprint('idphoto', __name__, url_prefix='/api/idphoto')

# 允许的文件扩展名
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'PNG', 'JPG', 'JPEG'}

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

# 处理证件照
@idphoto_bp.route('/process', methods=['POST'])
def process_photo():
    try:
        # 获取上传的文件
        if 'file' not in request.files:
            return jsonify({'code': 400, 'message': '没有上传文件'}), 400
        
        file = request.files['file']
        
        # 检查文件名
        if file.filename == '' or file.filename is None:
            return jsonify({'code': 400, 'message': '未选择文件'}), 400
        
        # 检查文件类型
        if not allowed_file(file.filename):
            return jsonify({'code': 400, 'message': '不支持的文件类型'}), 400
        
        # 获取处理设置
        settings = {
            'size': request.form.get('size', '1x'),
            'customWidth': 295,  # 默认值
            'customHeight': 413,  # 默认值
            'background': request.form.get('background', 'white'),
            'customColor': request.form.get('customColor', '#FFFFFF'),
            'removeWatermark': request.form.get('removeWatermark', 'false').lower() == 'true'
        }
        
        # 安全地转换自定义尺寸
        try:
            custom_width = request.form.get('customWidth')
            custom_height = request.form.get('customHeight')
            
            if custom_width is not None and custom_width != '':
                settings['customWidth'] = int(custom_width)
            if custom_height is not None and custom_height != '':
                settings['customHeight'] = int(custom_height)
        except (ValueError, TypeError):
            # 如果转换失败，使用默认值
            settings['customWidth'] = 295
            settings['customHeight'] = 413
        
        # 创建上传目录
        upload_dir = 'uploads'
        if not os.path.exists(upload_dir):
            os.makedirs(upload_dir)
        
        # 保存上传的文件
        filename = secure_filename(file.filename)
        if not filename:
            filename = 'uploaded_image.jpg'  # 默认文件名
            
        file_path = os.path.join(upload_dir, filename)
        file.save(file_path)
        
        # 检查文件是否保存成功
        if not os.path.exists(file_path):
            return jsonify({'code': 500, 'message': '文件保存失败'}), 500
        
        # 处理图片
        result = process_id_photo(file_path, settings)
        
        return jsonify({
            'code': 200,
            'message': '处理成功',
            'data': result
        }), 200
        
    except Exception as e:
        # 打印详细的错误信息
        error_info = traceback.format_exc()
        print(f"处理证件照错误: {e}")
        print(f"详细错误信息: {error_info}")
        return jsonify({'code': 500, 'message': f'处理失败: {str(e)}'}), 500

# 如果直接运行此文件，启动一个简单的测试服务器
if __name__ == '__main__':
    from flask import Flask
    app = Flask(__name__)
    app.register_blueprint(idphoto_bp)
    
    @app.route('/')
    def index():
        return 'ID Photo API Server'
    
    app.run(debug=True, port=5001)